
package cartagows.wsframework.wssecurity.policy.builders;

import java.util.Iterator;
import java.util.List;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMElement;
import org.apache.neethi.Assertion;
import org.apache.neethi.AssertionBuilderFactory;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.neethi.builders.AssertionBuilder;
import org.apache.neethi.builders.xml.XmlPrimtiveAssertion;

import cartagows.wsframework.wssecurity.policy.SP11Constants;
import cartagows.wsframework.wssecurity.policy.SPConstants;
import cartagows.wsframework.wssecurity.policy.model.RecipientToken;
import cartagows.wsframework.wssecurity.policy.model.Token;

public class RecipientTokenBuilder implements AssertionBuilder {

    public Assertion build(OMElement element, AssertionBuilderFactory factory)
            throws IllegalArgumentException {
        RecipientToken recipientToken = new RecipientToken(SPConstants.SP_V11);
        
        Policy policy = PolicyEngine.getPolicy(element.getFirstElement());
        policy = (Policy) policy.normalize(false);
        
        for (Iterator iterator = policy.getAlternatives(); iterator.hasNext();) {
            processAlternative((List) iterator.next(), recipientToken);
            
            /* 
             * for the moment we will pick the first token specified in the policy
             */
            break;   
        }
        
        return recipientToken;
    }

    private void processAlternative(List assertions, RecipientToken parent) {
        
        Assertion token;
        
        for (Iterator iterator = assertions.iterator(); iterator.hasNext();) {
            token = (Assertion) iterator.next();
            
            if(token.getName().getLocalPart().equals("UsernameToken")){
            	UsernameTokenBuilder utb = new UsernameTokenBuilder();
            	token = utb.build(((XmlPrimtiveAssertion ) token).getValue(), null);
            	
            }
            if(token.getName().getLocalPart().equals("X509Token")){
            	X509TokenBuilder xtb = new X509TokenBuilder();
            	token = xtb.build(((XmlPrimtiveAssertion ) token).getValue(), null);
            	
            }
            
            if (token instanceof Token) {
                parent.setToken((Token) token);
            }
        }        
    }
    
    public QName[] getKnownElements() {
        return new QName[] {SP11Constants.RECIPIENT_TOKEN};
    }

}
